import { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Popconfirm, Tag } from 'antd';
import { useFormik } from 'formik';
import moment from 'moment';

import type { TableColumnType } from 'antd';

import { mockUsers } from '@/utils/user';
import type { User } from '@/utils/user';

const dataSource = mockUsers();
const { Item: FormItem } = Form;

const DEFAULT_USER = {
  userId: '',
  username: '',
  email: '',
  password: '',
  avatar: '',
};

function App () {
  const [users, setUsers] = useState<any[]>(dataSource);
  const [visible, setVisible] = useState<any>(false);
  const [y, setY] = useState<number>(640);

  const onCancel = () => {
    setVisible(false);
  };

  const { values, setValues, handleChange, handleSubmit } = useFormik<any>({
    initialValues: DEFAULT_USER,
    onSubmit: (vls) => {
      const { userId } = vls;
      let editorUsers: any[] = [];
      users.forEach((u) => {
        if (u.userId === userId) {
          editorUsers.push(vls);
        } else {
          editorUsers.push(u);
        }
      });
      setUsers(editorUsers);
      onCancel();
    },
  });

  const editor = (user: any) => {
    setVisible(true);
    setValues(user);
  };

  const columns: TableColumnType<User>[] = [
    {
      title: 'Option',
      dataIndex: 'userId',
      fixed: 'left',
      width: 130,
      key: 'userId',
      render (_: string, record: User) {
        return (
          <>
            <Button onClick={() => editor(record)} size="small">
              Edit
            </Button>
            <Popconfirm title="Confirm Delete?">
              <Button size="small">Delete</Button>
            </Popconfirm>
          </>
        );
      },
    },
    {
      title: 'Name',
      dataIndex: 'username',
      key: 'name',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'Tags',
      dataIndex: 'tags',
      render (item) {
        return item.map((i: string) => <Tag color="red">{i}</Tag>);
      },
      key: 'tags',
    },
    {
      title: 'Brith Date',
      dataIndex: 'birthdate',
      key: 'birthdate',
      render (text: Date) {
        return moment(text).format('YYYY-MM-DD');
      },
    },
  ];

  useEffect(() => {
    let header = document.querySelector('#header');
    if (header) {
      header.setAttribute(
        'style',
        'color: red; padding: 12px; font-size: 24px'
      );

      const bodyHeight = document.documentElement.clientHeight;
      const headerHeight = header.clientHeight;
      const scrollHeight = bodyHeight - headerHeight - 120;
      setY(scrollHeight);
    }
  }, []);

  return (
    <div>
      <div id="header">Header</div>
      <Table
        dataSource={users}
        bordered
        columns={columns}
        rowKey="userId"
        scroll={{ x: 1100, y: y }}
      />
      <Modal
        visible={visible}
        title="Edit User"
        onCancel={onCancel}
        onOk={() => handleSubmit()}
      >
        <Form>
          <FormItem label="Name">
            <Input
              value={values.username}
              onChange={handleChange('username')}
            />
          </FormItem>
          <FormItem label="Email">
            <Input value={values.email} onChange={handleChange('email')} />
          </FormItem>
        </Form>
      </Modal>
    </div>
  );
}

export default App;
